require "rubygems"
require "mini_magick"
require "csv"
require "open-uri"
require "thread"

class GenerateLogo
  def initialize
    @csv = File.expand_path("../logo.csv", __FILE__)
    @pwd = File.dirname(File.expand_path(__FILE__))
    @names = []
    @valid_merchants = {}
    @threads = []
    @mutex = Mutex.new
  end
  
  def go
    puts "Starting ..."
    get_names
    puts "Downloading #{@names.size} files ..."
    get_images
    make_sql
    puts "Finished ..."
  end
  
  protected 
  
  def get_names
    reader = CSV::open(@csv, "r")
    reader.shift
    reader.each do |row| 
      @names << row[0].to_s
      if row[3]
        @valid_merchants[row[3].to_s] = row[0].to_s
      end
    end
  end
  
  def get_images
    @names.each do |name|
      @threads << Thread.new do
        image = "http://minishop.linktech.cn/images/logo/logo_#{name}.gif"
        logo = File.join(@pwd, "logos", "logo_"+name+".gif")
        begin          
          stream = open(image) { |f| f.read }
        rescue Exception => e
          @mutex.synchronize { puts image }
          raise StandardError
        end
        open(logo, "wb") { |f| f.write(stream)}
      end
    end
    
    @threads.each do |t| 
      begin        
        t.join
      rescue Exception => e
        next
      end
    end
  end
  
  def make_sql
    f = open(File.join(@pwd, "update_merchant_logo.sql"), "wb")
    @valid_merchants.each do |key, value|
      f.puts("UPDATE Merchant SET LogoFile='%08d_logo.GIF', BigLogoFile='b%08d_logo.GIF' WHERE MerchantID=%d;" % [key, key, key])
    end
    f.close
  end
end

if __FILE__ == $0
  # TODO Generated stub
  GenerateLogo.new.go
end